{% extends 'base.html' %}
{% load static %}

{% block title %}创建活动 - 本地有约{% endblock %}

{% block extra_css %}
<style>
    .form-control:focus {
        border-color: var(--primary-color);
        box-shadow: 0 0 0 0.2rem rgba(111, 66, 193, 0.25);
    }
    
    .btn-primary {
        background: var(--gradient-primary);
        border: none;
        transition: all 0.3s ease;
    }
    
    .btn-primary:hover {
        transform: translateY(-2px);
        box-shadow: 0 6px 20px rgba(111, 66, 193, 0.4);
    }
    
    .alert {
        border-radius: 0.5rem;
        margin-bottom: 1rem;
    }
    
    .create-container {
        max-width: 900px;
        margin: 2rem auto;
    }
    
    .form-section {
        background: white;
        border-radius: 1rem;
        padding: 2rem;
        box-shadow: var(--shadow-md);
        margin-bottom: 2rem;
    }
    
    .section-header {
        display: flex;
        align-items: center;
        gap: 1rem;
        margin-bottom: 1.5rem;
        padding-bottom: 1rem;
        border-bottom: 2px solid var(--border-color);
    }
    
    .section-icon {
        width: 48px;
        height: 48px;
        background: var(--gradient-primary);
        border-radius: 0.5rem;
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        font-size: 1.5rem;
    }
    
    .image-upload-box {
        border: 2px dashed var(--border-color);
        border-radius: 1rem;
        padding: 3rem;
        text-align: center;
        cursor: pointer;
        transition: all 0.3s ease;
        background: var(--light-bg);
    }
    
    .image-upload-box:hover {
        border-color: var(--primary-color);
        background: white;
    }
    
    .image-preview {
        max-width: 100%;
        max-height: 300px;
        border-radius: 0.5rem;
        margin-top: 1rem;
    }
    
    .char-counter {
        text-align: right;
        font-size: 0.85rem;
        color: var(--gray-text);
        margin-top: 0.25rem;
    }
    
    .location-autocomplete {
        position: relative;
    }
    
    .location-suggestions {
        position: absolute;
        width: 100%;
        max-height: 200px;
        overflow-y: auto;
        background: white;
        border: 1px solid var(--border-color);
        border-radius: 0.5rem;
        box-shadow: var(--shadow-lg);
        z-index: 1000;
        display: none;
    }
    
    .location-suggestion-item {
        padding: 0.75rem 1rem;
        cursor: pointer;
        transition: background-color 0.2s ease;
    }
    
    .location-suggestion-item:hover {
        background-color: var(--light-bg);
    }
</style>
{% endblock %}

{% block content %}
<div class="create-container">
    <h1 class="section-title">创建新活动</h1>
    
    <!-- 错误或成功提示 -->
    <div id="messageContainer" class="mb-4"></div>
    
    <form id="activityForm" enctype="multipart/form-data">
        <!-- 基本信息 -->
        <div class="form-section">
            <div class="section-header">
                <div class="section-icon">
                    <i class="fas fa-info-circle"></i>
                </div>
                <h2>基本信息</h2>
            </div>
            
            <div class="mb-3">
                <label for="title" class="form-label">活动标题 *</label>
                <input type="text" class="form-control" id="title" name="title" placeholder="给你的活动起个吸引人的名字" required maxlength="50">
                <div class="char-counter"><span id="titleCount">0</span>/50</div>
            </div>
            
            <div class="mb-3">
                <label for="activityType" class="form-label">活动类型 *</label>
                <select class="form-control" id="activityType" name="activityType" required>
                    <option value="">请选择活动类型</option>
                    {% for type in activity_types %}
                    <option value="{{ type.id }}">{{ type.name }}</option>
                    {% endfor %}
                </select>
            </div>
            
            <div class="mb-3">
                <label for="description" class="form-label">活动描述 *</label>
                <textarea class="form-control" id="description" name="description" rows="6" placeholder="详细介绍你的活动内容、亮点和期望" required maxlength="1000"></textarea>
                <div class="char-counter"><span id="descriptionCount">0</span>/1000</div>
            </div>
        </div>
        
        <!-- 时间地点 -->
        <div class="form-section">
            <div class="section-header">
                <div class="section-icon">
                    <i class="fas fa-calendar-alt"></i>
                </div>
                <h2>时间地点</h2>
            </div>
            
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label for="startTime" class="form-label">开始时间 *</label>
                    <input type="datetime-local" class="form-control" id="startTime" name="startTime" required>
                </div>
                <div class="col-md-6 mb-3">
                    <label for="endTime" class="form-label">结束时间 *</label>
                    <input type="datetime-local" class="form-control" id="endTime" name="endTime" required>
                </div>
            </div>
            
            <div class="mb-3">
                <label for="registrationDeadline" class="form-label">报名截止时间</label>
                <input type="datetime-local" class="form-control" id="registrationDeadline" name="registrationDeadline">
                <div class="form-text">不填写则默认为活动开始时间</div>
            </div>
            
            <div class="mb-3">
                <label for="locationName" class="form-label">活动地点名称 *</label>
                <input type="text" class="form-control" id="locationName" name="locationName" placeholder="例如：城市中心公园、XX咖啡馆" required>
            </div>
            
            <div class="mb-3 location-autocomplete">
                <label for="locationAddress" class="form-label">详细地址 *</label>
                <input type="text" class="form-control" id="locationAddress" name="locationAddress" placeholder="请输入详细地址，以便参与者导航" required>
                <div id="locationSuggestions" class="location-suggestions"></div>
            </div>
            
            <input type="hidden" id="latitude" name="latitude" value="0">
            <input type="hidden" id="longitude" name="longitude" value="0">
        </div>
        
        <!-- 费用与参与人数 -->
        <div class="form-section">
            <div class="section-header">
                <div class="section-icon">
                    <i class="fas fa-ticket-alt"></i>
                </div>
                <h2>费用与参与人数</h2>
            </div>
            
            <div class="mb-3">
                <div class="form-check form-switch">
                    <input class="form-check-input" type="checkbox" id="isFree" name="isFree" checked onchange="toggleFeeField()">
                    <label class="form-check-label" for="isFree">免费活动</label>
                </div>
            </div>
            
            <div class="mb-3" id="feeContainer" style="display: none;">
                <label for="fee" class="form-label">活动费用</label>
                <div class="input-group">
                    <span class="input-group-text">¥</span>
                    <input type="number" class="form-control" id="fee" name="fee" min="0" step="0.01" value="0">
                </div>
            </div>
            
            <div class="mb-3">
                <label for="maxParticipants" class="form-label">最大参与人数 *</label>
                <input type="number" class="form-control" id="maxParticipants" name="maxParticipants" min="1" required>
            </div>
            
            <div class="mb-3">
                <div class="form-check form-switch">
                    <input class="form-check-input" type="checkbox" id="allowGroupRegistration" name="allowGroupRegistration" onchange="toggleGroupDiscountField()">
                    <label class="form-check-label" for="allowGroupRegistration">允许团队报名</label>
                </div>
            </div>
            
            <div class="mb-3" id="groupDiscountContainer" style="display: none;">
                <label for="groupDiscount" class="form-label">团队折扣（百分比）</label>
                <div class="input-group">
                    <input type="number" class="form-control" id="groupDiscount" name="groupDiscount" min="0" max="99" step="1" value="0">
                    <span class="input-group-text">%</span>
                </div>
            </div>
        </div>
        
        <!-- 活动图片 -->
        <div class="form-section">
            <div class="section-header">
                <div class="section-icon">
                    <i class="fas fa-image"></i>
                </div>
                <h2>活动图片</h2>
            </div>
            
            <div class="mb-3">
                <label for="coverImage" class="form-label">封面图片</label>
                <div class="image-upload-box" onclick="document.getElementById('coverImage').click()">
                    <i class="fas fa-cloud-upload-alt fa-3x text-muted"></i>
                    <p class="mt-2">点击或拖拽图片到此处上传</p>
                    <p class="text-sm text-muted">支持JPG、PNG、GIF等格式，大小不超过10MB</p>
                    <input type="file" id="coverImage" name="coverImage" accept="image/*" style="display: none;">
                </div>
                <div id="imagePreviewContainer" class="mt-3" style="display: none;">
                    <img id="imagePreview" src="" alt="图片预览" class="image-preview">
                    <button type="button" class="btn btn-link text-danger mt-1" onclick="removeImage()">
                        <i class="fas fa-trash-alt"></i> 删除图片
                    </button>
                </div>
            </div>
        </div>
        
        <!-- 提交按钮 -->
        <div class="text-center mb-4">
            <button type="button" class="btn btn-secondary me-3" onclick="history.back()">取消</button>
            <button type="submit" class="btn btn-primary px-6 py-2">
                <i class="fas fa-paper-plane"></i> 发布活动
            </button>
        </div>
    </form>
</div>
{% endblock %}

{% block extra_js %}
<script>
    document.addEventListener('DOMContentLoaded', function() {
        // 字符计数器
        document.getElementById('title').addEventListener('input', function() {
            document.getElementById('titleCount').textContent = this.value.length;
        });
        
        document.getElementById('description').addEventListener('input', function() {
            document.getElementById('descriptionCount').textContent = this.value.length;
        });
        
        // 图片上传预览
        document.getElementById('coverImage').addEventListener('change', function(e) {
            if (e.target.files && e.target.files[0]) {
                const reader = new FileReader();
                
                reader.onload = function(event) {
                    document.getElementById('imagePreview').src = event.target.result;
                    document.getElementById('imagePreviewContainer').style.display = 'block';
                }
                
                reader.readAsDataURL(e.target.files[0]);
            }
        });
        
        // 表单提交
        document.getElementById('activityForm').addEventListener('submit', function(e) {
            e.preventDefault();
            submitActivity();
        });
        
        // 初始化日期时间
        const now = new Date();
        now.setMinutes(now.getMinutes() - now.getTimezoneOffset());
        const dateString = now.toISOString().slice(0, 16);
        document.getElementById('startTime').min = dateString;
        document.getElementById('endTime').min = dateString;
        document.getElementById('registrationDeadline').min = dateString;
    });
    
    // 切换费用字段显示
    function toggleFeeField() {
        const isFree = document.getElementById('isFree').checked;
        document.getElementById('feeContainer').style.display = isFree ? 'none' : 'block';
    }
    
    // 切换团队折扣字段显示
    function toggleGroupDiscountField() {
        const allowGroup = document.getElementById('allowGroupRegistration').checked;
        document.getElementById('groupDiscountContainer').style.display = allowGroup ? 'block' : 'none';
    }
    
    // 移除图片
    function removeImage() {
        document.getElementById('coverImage').value = '';
        document.getElementById('imagePreviewContainer').style.display = 'none';
    }
    
    // 提交活动
    function submitActivity() {
        // 验证表单
        if (!validateForm()) {
            return;
        }
        
        // 显示加载状态
        showLoading(true);
        
        // 先上传图片（如果有）
        const coverImageInput = document.getElementById('coverImage');
        const hasImage = coverImageInput.files && coverImageInput.files.length > 0;
        
        if (hasImage) {
            uploadImage(coverImageInput.files[0])
                .then(imageUrl => {
                    // 图片上传成功后提交活动数据
                    submitActivityData(imageUrl);
                })
                .catch(error => {
                    showLoading(false);
                    showMessage('图片上传失败，请重试', 'error');
                    console.error('图片上传失败:', error);
                });
        } else {
            // 没有图片直接提交活动数据
            submitActivityData('');
        }
    }
    
    // 上传图片
    function uploadImage(imageFile) {
        return new Promise((resolve, reject) => {
            const formData = new FormData();
            formData.append('image', imageFile);
            
            fetch('{% url 'activities:api_upload_image' %}', {
                method: 'POST',
                headers: {
                    'X-CSRFToken': getCSRFToken(),
                },
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    resolve(data.data.url);
                } else {
                    reject(new Error(data.message || '上传失败'));
                }
            })
            .catch(error => {
                reject(error);
            });
        });
    }
    
    // 提交活动数据
    function submitActivityData(coverImageUrl) {
        const activityData = {
            title: document.getElementById('title').value,
            description: document.getElementById('description').value,
            activity_type: document.getElementById('activityType').value,
            start_time: document.getElementById('startTime').value,
            end_time: document.getElementById('endTime').value,
            registration_deadline: document.getElementById('registrationDeadline').value || null,
            location_name: document.getElementById('locationName').value,
            location_address: document.getElementById('locationAddress').value,
            latitude: parseFloat(document.getElementById('latitude').value),
            longitude: parseFloat(document.getElementById('longitude').value),
            max_participants: parseInt(document.getElementById('maxParticipants').value),
            is_free: document.getElementById('isFree').checked,
            fee: document.getElementById('isFree').checked ? 0 : parseFloat(document.getElementById('fee').value || 0),
            status: 'published',
            allow_group_registration: document.getElementById('allowGroupRegistration').checked,
            group_discount: document.getElementById('allowGroupRegistration').checked ? parseFloat(document.getElementById('groupDiscount').value || 0) : 0,
            cover_image: coverImageUrl
        };
        
        fetch('{% url 'activities:api_create' %}', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': getCSRFToken(),
            },
            body: JSON.stringify(activityData)
        })
        .then(response => response.json())
        .then(data => {
            showLoading(false);
            
            if (data.code === 200) {
                showMessage('活动创建成功！', 'success');
                // 跳转到活动详情页
                setTimeout(() => {
                    window.location.href = '{% url 'activities:detail' 0 %}'.replace('0', data.data.id);
                }, 1500);
            } else {
                showMessage(data.message || '创建活动失败，请重试', 'error');
            }
        })
        .catch(error => {
            showLoading(false);
            showMessage('网络错误，请稍后重试', 'error');
            console.error('创建活动失败:', error);
        });
    }
    
    // 验证表单
    function validateForm() {
        const title = document.getElementById('title').value.trim();
        const description = document.getElementById('description').value.trim();
        const activityType = document.getElementById('activityType').value;
        const startTime = document.getElementById('startTime').value;
        const endTime = document.getElementById('endTime').value;
        const locationName = document.getElementById('locationName').value.trim();
        const locationAddress = document.getElementById('locationAddress').value.trim();
        const maxParticipants = document.getElementById('maxParticipants').value;
        
        if (!title) {
            showMessage('请输入活动标题', 'error');
            return false;
        }
        
        if (!description) {
            showMessage('请输入活动描述', 'error');
            return false;
        }
        
        if (!activityType) {
            showMessage('请选择活动类型', 'error');
            return false;
        }
        
        if (!startTime) {
            showMessage('请选择开始时间', 'error');
            return false;
        }
        
        if (!endTime) {
            showMessage('请选择结束时间', 'error');
            return false;
        }
        
        if (new Date(startTime) >= new Date(endTime)) {
            showMessage('结束时间必须晚于开始时间', 'error');
            return false;
        }
        
        if (!locationName) {
            showMessage('请输入活动地点名称', 'error');
            return false;
        }
        
        if (!locationAddress) {
            showMessage('请输入详细地址', 'error');
            return false;
        }
        
        if (!maxParticipants || maxParticipants < 1) {
            showMessage('请输入有效的最大参与人数', 'error');
            return false;
        }
        
        return true;
    }
    
    // 显示消息
    function showMessage(message, type = 'info') {
        const container = document.getElementById('messageContainer');
        const alertClass = type === 'success' ? 'alert-success' : 
                          type === 'error' ? 'alert-danger' : 'alert-info';
        const iconClass = type === 'success' ? 'fas fa-check-circle' : 
                         type === 'error' ? 'fas fa-exclamation-circle' : 'fas fa-info-circle';
        
        container.innerHTML = `
            <div class="alert ${alertClass} alert-dismissible fade show" role="alert">
                <i class="${iconClass}"></i> ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        `;
    }
    
    // 显示加载状态
    function showLoading(show) {
        const submitButton = document.querySelector('button[type="submit"]');
        if (show) {
            submitButton.disabled = true;
            submitButton.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 发布中...';
        } else {
            submitButton.disabled = false;
            submitButton.innerHTML = '<i class="fas fa-paper-plane"></i> 发布活动';
        }
    }
    
    // 获取CSRF令牌
    function getCSRFToken() {
        const cookieValue = document.cookie
            .split('; ')
            .find(row => row.startsWith('csrftoken='))
            ?.split('=')[1];
        return cookieValue ? decodeURIComponent(cookieValue) : '';
    }
</script>
{% endblock %}
